home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 7542 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.8 KB  |  64 lines

  1. Path: keats.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Why does this work?
  5. Date: 25 Feb 1996 12:19:04 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4gqg7oINN26a@keats.ugrad.cs.ubc.ca>
  8. References: <4g8f7o$adt@ncar.ucar.edu> <4ggsi6$1fg@dopey.magg.net>
  9. NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
  10.  
  11. In article <4ggsi6$1fg@dopey.magg.net>, Dennis Hawkins <n4mwd@magg.net> wrote:
  12.  >rosinski@ra.cgd.ucar.edu (Jim Rosinski) wrote:
  13.  >
  14.  >>Could someone please explain why the following code works?  In particular, I
  15.  >>am perplexed as to why "sub1" and "sub2" declared as elements of "cmndtable"
  16.  >
  17.  >>#include <stdio.h>
  18.  >>main()
  19.  >>{
  20.  >>  void sub1(), sub2();
  21.  >
  22.  >>  struct cmndstruct {
  23.  >>    void (*funcnam)();
  24.  >>  };
  25.  >
  26.  >>  struct cmndstruct cmndtable[] = {
  27.  >>    sub1,
  28.  >>    sub2,
  29.  >>    NULL
  30.  >>  };
  31.  >>  struct cmndstruct *cmndptr;
  32.  >
  33.  >>  for (cmndptr = cmndtable; *(cmndptr->funcnam) != NULL; cmndptr++) {
  34.  >>    (*(cmndptr->funcnam))();
  35.  >>  }
  36.  >>  exit(0);
  37.  >>}
  38.  >
  39.  >>void sub1()
  40.  >>{
  41.  >>  printf("Inside sub1\n");
  42.  >>}
  43.  >
  44.  >>void sub2()
  45.  >>{
  46.  >>  printf("Inside sub2\n");
  47.  >>}
  48.  >
  49.  >There is nothing really all that unusual about your program.  The only
  50.  >thing that looks a little strange to me was that you have a structure
  51.  >with only one field in it.  A simple array of pointers to functions
  52.  
  53. He probably did that to underscore the fact that apparently functions are being
  54. assigned to structure types. You need only a single-membered structure to
  55. indicate that.
  56.  
  57.  >would be more efficient.  As far as the machine knows, that is
  58.  >precisely what you have here.
  59.  
  60. Maybe not. The alignment constraints for a structure could be different from
  61. those for bare function pointers. Though this is not likely in practice.
  62. -- 
  63.  
  64.